package com.zslin.business.tools.excel;

import com.zslin.business.dao.IOrdersDao;
import com.zslin.business.dao.IOrdersProductDao;
import com.zslin.business.dao.IProductSpecsDao;
import com.zslin.business.model.Orders;
import com.zslin.business.model.OrdersProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单处理工具能力
 */
@Component
public class OrdersExportTools {

    @Autowired
    private IOrdersDao ordersDao;

    @Autowired
    private IProductSpecsDao productSpecsDao;

    @Autowired
    private IOrdersProductDao ordersProductDao;

    /**
     * 获取订单数据
     * @param day 格式 yyyy-MM-dd
     * @return
     */
    public List<OrdersDto> buildData(String day) {
        List<Orders> ordersList = ordersDao.findByPayDay(day);
        List<OrdersDto> result = new ArrayList<>();
        for(Orders o : ordersList) {
            OrdersDto dto = new OrdersDto();
            dto.setAddress(rebuildStr(o.getAddressCon()));
            dto.setAgentName(rebuildStr(o.getAgentName()));
            dto.setAgentPhone(rebuildStr(o.getAgentPhone()));
            dto.setCreateTime(o.getCreateTime());
            dto.setDiscountMoney(rebuildFloat(o.getDiscountMoney()));
            dto.setHasAgent(o.getHasAgent());
            dto.setOrderNo(o.getOrdersNo());
            dto.setDiscountReason(rebuildStr(o.getDiscountReason()));
            dto.setPayMoney(rebuildFloat(o.getPayMoney()));
            dto.setPayTime(rebuildStr(o.getPayTime()));
            dto.setProTitles(o.getProTitles());
            dto.setStatus(rebuildStatus(o.getStatus()));
            dto.setTotalMoney(rebuildFloat(o.getTotalMoney()));
            dto.setSpecs(rebuildSpecs(o.getOrdersNo()));
            result.add(dto);
        }
        return result;
    }

    private String rebuildSpecs(String ordersNo) {
        List<OrdersProduct> productList = ordersProductDao.findByOrdersNo(ordersNo);
        StringBuffer sb = new StringBuffer();
        for(OrdersProduct op : productList) {
            sb.append(op.getSpecsName()).append("|");
        }
        return sb.toString();
    }

    private String rebuildStatus(String status) {
        if("1".equals(status)) {
            return "付款未发货";
        } else if("2".equals(status)) {
            return "已发货";
        } else if("3".equals(status) || "4".equals(status)) {
            return "已完成";
        } else if("-2".equals(status)) {
            return "存在售后";
        } else if("-1".equals(status)) {
            return "全额退款";
        } else {
            return "其他"+status;
        }
    }

    private Float rebuildFloat(Float f) {
        if(f==null) {return 0f;}
        return f;
    }

    private String rebuildStr(String str) {
        if(str==null) {return "";}
        return str;
    }
}
